import {
  smartEnglishBulkDeletes,
  smartEnglishCreate,
  smartEnglishIsFavorited,
  smartEnglishPagination,
  smartEnglishUpdate,
} from '@/services/swagger/smartEnglish';
import { HeartFilled, HeartOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProFormText,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, message, Select } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.VocabularyCreateInputModel) => {
  const hide = message.loading('正在添加');
  try {
    await smartEnglishCreate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Update learning status
 * @zh-CN 修改状态
 * @param fields
 */
const handleLearningStatus = async (id: number, status: number) => {
  const hide = message.loading('正在修改');
  try {
    await smartEnglishUpdate({ id: id, status: status as API.LearningStatus });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 * @en-US Toggle favorite
 * @zh-CN 是否收藏
 * @param fields
 */
const handleToggleFavorite = async (fields: API.VocabularyOutputModel) => {
  const hide = message.loading('正在修改');
  try {
    await smartEnglishIsFavorited({ id: fields.id as number });
    hide();
    if (fields.isFavorited) {
      message.success('取消收藏');
    } else {
      message.success('收藏成功');
    }
    return true;
  } catch (error) {
    hide();
    message.error('修改失败, 请再次重试!');
    return false;
  }
};

/**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: API.VocabularyOutputModel[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const ids = {
      ids: selectedRows.map((row) => row.id).join(','), // 示例 ID 列表
    } as API.SmartEnglishBulkDeletesParams;

    await smartEnglishBulkDeletes(ids);
    hide();
    message.success('删除成功');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败, 请再次重试！');
    return false;
  }
};

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.VocabularyOutputModel>();
  const [selectedRowsState, setSelectedRows] = useState<API.VocabularyOutputModel[]>([]);

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();

  const columns: ProColumns<API.VocabularyOutputModel>[] = [
    {
      title: (
        <FormattedMessage id="pages.searchTable.updateForm.word.wordLabel" defaultMessage="Word" />
      ),
      dataIndex: 'word',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: (
        <FormattedMessage
          id="pages.searchTable.updateForm.isFavorited.favoritedLabel"
          defaultMessage="Is favorited"
        />
      ),
      dataIndex: 'isFavorited',
      valueType: 'select',
      valueEnum: {
        true: { text: '收藏' },
        false: { text: '未收藏' },
      },
      render: (text, entity) => {
        return (
          <a
            onClick={() => {
              handleToggleFavorite(entity);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
          >
            {entity.isFavorited ? <HeartFilled style={{ color: 'red' }} /> : <HeartOutlined />}
          </a>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
      dataIndex: 'learningStatus',
      valueType: 'select',
      valueEnum: {
        0: { text: '未开始' },
        1: { text: '学习中' },
        2: { text: '已学会' },
      },
      render: (text, entity) => {
        return (
          <Select
            value={Number(entity.learningStatus)} // 确保将text转为数字
            onChange={(value) => {
              handleLearningStatus(entity.id as number, value as number);
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }}
            placeholder="Select status" // 可以添加一个占位符
          >
            <Select.Option value={0}>
              <FormattedMessage
                id="pages.searchTable.learningStatus.notStarted"
                defaultMessage="Not started"
              />
            </Select.Option>
            <Select.Option value={1}>
              <FormattedMessage
                id="pages.searchTable.learningStatus.inProgress"
                defaultMessage="In progress"
              />
            </Select.Option>
            <Select.Option value={2}>
              <FormattedMessage
                id="pages.searchTable.learningStatus.mastered"
                defaultMessage="Mastered"
              />
            </Select.Option>
          </Select>
        );
      },
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return <Select {...rest} placeholder="请选择"></Select>;
      },
    },
    // {
    //   title: <FormattedMessage id="pages.searchTable.titleStatus" defaultMessage="Status" />,
    //   dataIndex: 'learningStatus',
    //   hideInForm: true,
    //   valueType: 'select',
    //   valueEnum: {
    //     0: { text: '收藏' },
    //     1: { text: '未收藏' },
    //     3: { text: '未收藏' },
    //   },
    //   render: (text, entity) => (
    //     <Select
    //       value={Number(text)} // 确保将text转为数字
    //       onChange={(value) => {
    //         handleLearningStatus(entity.id as number, value as number);
    //         if (actionRef.current) {
    //           actionRef.current.reload();
    //         }
    //       }}
    //       placeholder="Select status" // 可以添加一个占位符
    //     >
    //       <Select.Option value={0}>
    //         <FormattedMessage
    //           id="pages.searchTable.learningStatus.notStarted"
    //           defaultMessage="Not started"
    //         />
    //       </Select.Option>
    //       <Select.Option value={1}>
    //         <FormattedMessage
    //           id="pages.searchTable.learningStatus.inProgress"
    //           defaultMessage="In progress"
    //         />
    //       </Select.Option>
    //       <Select.Option value={2}>
    //         <FormattedMessage
    //           id="pages.searchTable.learningStatus.mastered"
    //           defaultMessage="Mastered"
    //         />
    //       </Select.Option>
    //     </Select>
    //   ),
    // },
    {
      title: <FormattedMessage id="pages.searchTable.created" defaultMessage="Created time" />,
      sorter: true,
      dataIndex: 'created',
      valueType: 'dateTime',
      search: false,
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.VocabularyOutputModel, API.SmartEnglishPaginationParams>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.english.word.list',
          defaultMessage: 'Word list',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
          </Button>,
        ]}
        request={smartEnglishPagination}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="Chosen" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            <FormattedMessage
              id="pages.searchTable.batchDeletion"
              defaultMessage="Batch deletion"
            />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: 'pages.searchTable.createForm.newWord',
          defaultMessage: 'New word',
        })}
        width="400px"
        open={createModalOpen}
        onOpenChange={handleModalOpen}
        onFinish={async (value) => {
          const success = await handleAdd(value as API.VocabularyCreateInputModel);
          if (success) {
            handleModalOpen(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: (
                <FormattedMessage id="pages.searchTable.word" defaultMessage="Word is required" />
              ),
            },
          ]}
          width="md"
          name="word"
        />
      </ModalForm>
      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.word && (
          <div>
            <h2>{currentRow.word}</h2>
            {currentRow.description ? (
              <>
                {(() => {
                  try {
                    const descriptionObj = JSON.parse(currentRow.description);
                    console.log(descriptionObj);
                    const pronunciation = descriptionObj?.pronunciation;
                    const synonyms = descriptionObj?.results[0]?.synonyms || [];
                    const antonyms = descriptionObj?.results[0]?.antonyms || [];
                    const definition = descriptionObj?.results[0]?.definition;
                    descriptionObj?.results?.forEach((result: any) => {
                      console.log(result);
                    });
                    return (
                      <div>
                        <p>
                          发音：
                          {typeof pronunciation === 'string'
                            ? pronunciation
                            : JSON.stringify(pronunciation)}
                        </p>
                        {descriptionObj?.results?.map((result: any, index: number) => (
                          <div key={index} style={{ marginBottom: '50px' }}>
                            <p>定义：{result.definition ? result.definition : '无定义'}</p>
                            <p>词性：{result.partOfSpeech ? result.partOfSpeech : '无'}</p>
                            <p>
                              类型：
                              {Array.isArray(result.typeOf) && result.typeOf.length > 0
                                ? result.typeOf.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                            <p>
                              复合名词：
                              {Array.isArray(result.hasParts) && result.hasParts.length > 0
                                ? result.hasParts.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                            <p>
                              分类：
                              {Array.isArray(result.hasTypes) && result.hasTypes.length > 0
                                ? result.hasTypes.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                            <p>
                              组成：
                              {Array.isArray(result.partOf) && result.partOf.length > 0
                                ? result.partOf.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                            <p>
                              特定分类：
                              {Array.isArray(result.inCategory) && result.inCategory.length > 0
                                ? result.inCategory.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                            <p>
                              同义词：
                              {Array.isArray(result.synonyms) ? result.synonyms.join(', ') : '无'}
                            </p>
                            <p>
                              反义词：
                              {Array.isArray(result.antonyms) && result.antonyms.length > 0
                                ? result.antonyms.join(', ')
                                : '无'}
                            </p>
                            <p>
                              举例：
                              {Array.isArray(result.examples) && result.examples.length > 0
                                ? result.examples.map((example: string, idx: number) => (
                                    <div key={idx}>
                                      {idx + 1}. {example}
                                    </div>
                                  ))
                                : '无'}
                            </p>
                          </div>
                        ))}
                      </div>
                    );
                  } catch (error) {
                    return <p>Error parsing description.</p>;
                  }
                })()}
              </>
            ) : (
              <p>No description available.</p>
            )}
          </div>
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
